package com.linux.huhx.thread3.reentrantreadwrite_1;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: huhx
 * @Date: 2017-10-31 上午 10:19
 */
public class Service {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        try {
            lock.readLock().lock();
//            lock.writeLock().lock();
            System.out.println("Acquire read lock " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
//            lock.writeLock().unlock();
        }
    }

    public void write() {
        try {
            lock.writeLock().lock();
            System.out.println("Acquire write lock " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
}
